<html>
<head>
<script language="JavaScript">
    /**
     * Copyright (c) 2007 Wink Saville
     *
     * Licensed under GPLv2
     */

	/**
	 * 1000 causes Firefox to crash, possibly
	 * because messages were lost when the
	 * server closes the connections every
	 * 100 messages.
	 */
	os = new Array;
	or = new Array;
	seqNum = 0;
	fullDebug = false;

	function debug(s)
	{
		if (fullDebug)
		{
			if (console == null)
			{
				dw = document.getElementById("debug");
				if (dw)
					dw.value += s + "\n";
			}
			else
				console.debug(s + "\n");
		}
	}

	function debug2(s)
	{
		dw = document.getElementById("debug");
		if (dw)
			dw.value += s + "\n";
	}

	function send(o, c, sn)
	{
		debug2("send 1");
		o.req.open("POST", "/amc", true);
		debug2("send 2");
		o.req.onreadystatechange = function ()
		{
    		debug2("send x o.sn=" + o.sn + " readyState=" + o.req.readyState);
			if (o.req.readyState == 4)
			{		
        		debug2("send y o.sn=" + o.sn + " readyState=" + o.req.readyState);
				rslt = o.req.responseText;
				o.reply = true;
				debug2("send: z o.sn=" + o.sn + " status='" + o.req.status + "' rslt='" + rslt + "'");

			}
		}

		d = "{\"4\":[ 1,\"urn\",\"friendly-name\"]}";
		o.req.setRequestHeader("Content-length", d.length);
		o.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		debug2("send: 3 sn=" + o.sn + " " + d);
		o.req.send(d);
		debug2("sent: 4 sn=" + o.sn + " " + d);
	}

	function recv(o, c, sn)
	{
		o.req.open("GET", "/amc", true);
		o.req.onreadystatechange = function ()
		{
			if (o.req.readyState == 4)
			{		
				rslt = o.req.responseText.split("&");
				o.reply = true;
				debug2("recv: recvd cmd=" + rslt[0] + " c=" + rslt[1] + " sn=" + rslt[2]);
			}
		}
		o.req.send(null);
		debug2("recv sent: ");
	}
	
	function test()
	{
		debug2("test");
		os = new Array;
		or = new Array;
		for (i = 0; i < document.getElementById("times").value; i++)
		{
			o = new Object;
			o.req = new XMLHttpRequest();
			o.sn = i;
			o.reply = false;
			os[i] = o;
			o = new Object;
			o.req = new XMLHttpRequest();
			o.sn = -i;
			o.reply = false;
			or[i] = o;
		}

		debug2("test start send/recv");
		for (i=0; i < os.length; i++)
		{
			send(os[i], i, seqNum++);
			//recv(or[i], i, seqNum++);
	       	}
		debug2("test done send/recv");
	}

</script>
</head
<body>
<input type="button" id="my_button" onClick="test();" value="test"/>
<input type="text" id="times" value="1"/>
<br/>
<textarea id="debug" rows="10" cols="40"></textarea>
<br/>
</body>
</html>
